<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form isheader" v-if="headerShow">
                <div>
                    <a-form size="mini" :model="pageData" layout="inline"
                        v-if="permissionStore.hasPermisson('cgdjdcx.cx1')">
                        <a-form-item label="采购单号" label-col-flex="60px">
                            <a-input class="bacClass" placeholder="" v-model="pageData.purchaseCode" @press-enter="huiche"
                                allow-clear  style="width:150px"/>
                        </a-form-item>
                        <a-form-item label="编制日期" field="purchaseDate" label-col-flex="60px">
                            <a-date-picker  popup-container="html"  class="bacClass" placeholder="" :time-picker-props="{ defaultValue: '00:00:00' }"
                                format="YYYY-MM-DD" v-model="pageData.beginTime" style="width:150px"/>至
                            <a-date-picker  popup-container="html"  class="bacClass" placeholder="" :time-picker-props="{ defaultValue: '00:00:00' }"
                                format="YYYY-MM-DD" v-model="pageData.endTime" style="width:150px"/>
                        </a-form-item>
                        <a-form-item label="采购商" label-col-flex="60px">
                            <a-input class="bacClass" placeholder="" v-model="pageData.providerName" @press-enter="huiche" style="width:162px"
                                allow-clear />
                        </a-form-item>
                        <a-form-item label="物料编号" label-col-flex="60px"> 
                            <a-input class="bacClass" placeholder="" v-model="pageData.materialCode" @press-enter="huiche" style="width:150px"
                                allow-clear />
                        </a-form-item>
                        <a-form-item label="主体" label-col-flex="60px">
                            <a-select popup-container="html"  class="bacClass" :loading="loading" @search="handleSearchZt"
                                v-model="pageData.companyEntity" style="width:150px" :filter-option="false" allow-search
                                allow-clear @focus="focusSelZt">
                                <a-option v-for="item in pageData.companyEntityList" :value="item['company_entity']">{{
                                    item['company_entity']
                                }}</a-option>
                            </a-select>
                        </a-form-item>

                    </a-form>
                </div>
                <div>
                    <!-- @dyBoufei="handleClick" -->
                    <Toolbar class="gesture"
                        :items="pageData.btnList"
                        @select="selectSh" @export="exports">
                    </Toolbar>

                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
            </div>
        </template>
        <template #pageTabel>

            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady"
                    style="height: 100%" :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList"
                    :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
            </a-spin>

        </template>
        <paginationCopys :page-size-options="pagingList1" :total="pagination.total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="pagination.pageSize"
            :current="pagination.page" />
    </pageTabelLayout>
</template>
  
<script setup lang="ts" >
import { reactive, ref, onMounted } from 'vue'
import { post } from '@/api/http'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import PostType from '@/views/organizational/PostType.vue'
import printJS from 'print-js'
import dayjs from 'dayjs'
import XqService from '../orderpurchase/service/xq/index'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import usePermission from '@/store/modules/permission'

const { selectedRowKeys, onSelectionChange } = useRowSelection()
const rowKey = useRowKey('id')
const pagination = usePagination(doRefresh)
const table = useTable()
const formRef = ref()
let idDtaDy: any = ref([])
let dataTime = ref([])

function change1(val: any) {
    pagination.pageSize = val
    doRefresh()
}

function PageSize(val: any) {
    pagination.page = val
    doRefresh()
}
const localeText1: any = ref(localeText)
const pagingList1: any = ref(pagingList)
function doRefresh() {
    pageData.pageLoading = true
    post({
        url: 'dwPurchase/PurchaseOrderDetail/getOrderSchedule',
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            purchaseCode: pageData.purchaseCode,
            providerName: pageData.providerName,
            materialCode: pageData.materialCode,
            beginTime: pageData.beginTime,
            endTime: pageData.endTime,
            companyEntity: pageData.companyEntity

        },
    })
        .then(({ data, code }: any) => {
            if (code === 200) {
                table.handleSuccess(data.list)
                pagination.setTotalSize(data.total)
                gridOption.value.setRowData(data.list)
            }
        })
        .catch(console.log)
        .finally(() => {
            pageData.pageLoading = false
        })
}

const pageData = reactive<{
    showAdd: boolean
    sideTitle: string
    dropDownData: any
    pageLoading: boolean
    loading: boolean
    purchaseCode: any
    providerName: any
    materialCode: any
    beginTime: any
    endTime: any
    companyEntity: any
    companyEntityList: any[]
    btnList:any[]
}>({
    loading: false,
    showAdd: false,
    sideTitle: '新增产品基础资料',
    dropDownData: '',
    pageLoading: false,
    purchaseCode: "",
    providerName: "",
    materialCode: "",
    beginTime: "",
    endTime: "",
    companyEntity: "",
    companyEntityList: [],
    btnList:[]
})
const headerShow = ref<boolean>(true)
const tableColumns = useTableColumn([
    {
        title: '建单日期',
        key: 'purchaseDate',
        dataIndex: 'purchaseDate',
        width: 150,
    },
    {
        title: '物料编号',
        key: 'materialCode',
        dataIndex: 'materialCode',
        width: 150,
    },
    {
        title: '物料名称',
        key: 'materialName',
        dataIndex: 'materialName',
        width: 150,
    },
    {
        title: '采购单号',
        key: 'purchaseCode',
        dataIndex: 'purchaseCode',
        width: 150,
    },
    {
        title: '采购数量',
        key: 'purchaseNum',
        dataIndex: 'purchaseNum',
        width: 150,
    },
    {
        title: '单价',
        key: 'price',
        dataIndex: 'price',
        width: 150,
    },
    {
        title: '采购单位',
        key: 'purchaseUnit',
        dataIndex: 'purchaseUnit',
        width: 150,
    },
    {
        title: '换算比例',
        key: 'convertRate',
        dataIndex: 'convertRate',
        width: 150,
    },
    {
        title: '换算后数量',
        key: 'purchaseNumCon',
        dataIndex: 'purchaseNumCon',
        width: 150,
    },
    {
        title: '入库数量',
        key: 'inStockNum',
        dataIndex: 'inStockNum',
        width: 150,
    },
    {
        title: '主体单位',
        key: 'companyEntity',
        dataIndex: 'companyEntity',
        width: 150,
    },
    {
        title: '未入库数量',
        key: 'notInStockNum',
        dataIndex: 'notInStockNum',
        width: 150,
    },
    {
        title: '税号',
        key: 'dutyParagraph',
        dataIndex: 'dutyParagraph',
        width: 150,
    },
    {
        title: '采购公司',
        key: 'useCompanyName',
        dataIndex: 'useCompanyName',
        width: 150,
    },
    {
        title: '换算后单价',
        key: 'price',
        dataIndex: 'price',
        width: 150,
    },
    {
        title: '单位',
        key: 'unit',
        dataIndex: 'unit',
        width: 150,
    },
    {
        title: '申购单审核日期',
        key: 'auditDate',
        dataIndex: 'auditDate',
        width: 150,
    },
    {
        title: '计划交货日期',
        key: 'planDeliveryDate',
        dataIndex: 'planDeliveryDate',
        width: 150,
    },
    {
        title: '实际交货日期',
        key: 'stockInDate',
        dataIndex: 'stockInDate',
        width: 150,
    },
    {
        title: '延期日期',
        key: 'extensionDay',
        dataIndex: 'extensionDay',
        width: 150,
    },
    {
        title: '供应商',
        key: 'providerName',
        dataIndex: 'providerName',
        width: 150,
    },
    {
        title: '采购制单人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
    },
    {
        title: '状态',
        key: 'infoState',
        dataIndex: 'infoState',
        slotName: 'infoState',
        fixed: 'right',
        width: 150,
    },
])

onMounted(() => {
    emitter.on('PurchaseOrderProgressQuery', () => {
        doRefresh()
    })

})

interface SettlementType {

}
const dataForm = reactive<SettlementType>({

})



const selectSh = () => {
    pagination.page = 1
    doRefresh()
}



const gridOption = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
}
let tc: any[] = tableColumns.map((o) => {
    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
    }
    if (o.slotName === 'infoState') {
        obj['width'] = 100
        obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0'
          ? '未完成'
          : params.value == '1'
          ? '已完成'
          : params.value == '2'
          ? '手工完成'
          : ''
      },
    }
        obj['cellRenderer'] = {
            template: `
            <el-tag v-if="isDatas.infoState == 0" type="warning">未完成
                        </el-tag>
                        <el-tag v-if="isDatas.infoState == 1" type="success">已完成
                        </el-tag>
                        <el-tag v-if="isDatas.infoState == 2">手工完成
                        </el-tag>`,
            setup(props: any) {
                const isDatas = ref(props.params.data)
                return {
                    isDatas,
                }
            },
        }
    }
    return obj
})
const huiche = () => {
    selectSh()
}
let a = [
    {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
    },
]
tc = a.concat(tc)

const permissionStore = usePermission()
//导出
const exports = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
    } else {
        //将表头拼接出来
        let head =
            '<th>编制日期</th><th>物料编号</th><th>物料名称</th><th>采购单号</th><th>采购数量</th><th>单价</th><th>采购单位</th><th>换算比例</th><th>换算后数量</th><th>入库数量</th><th>主体单位</th><th>未入库数量</th><th>税号</th><th>采购公司</th><th>换算后单价</th><th>单位</th><th>交货日期</th><th>供应商</th><th>采购制单人</th><th>状态</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = gridOption.value.getSelectedRows()
        let body = ''
        nowRow.forEach(function (o) {
            body += '<tr><td>' + (o['purchaseDate'] == undefined ? "" : o['purchaseDate']) + '</td>'
            body += '<td>' + (o['materialCode'] == undefined ? "" : o['materialCode']) + '</td>'
            body += '<td>' + (o['materialName'] == undefined ? "" : o['materialName']) + '</td>'
            body += '<td>' + (o['purchaseCode'] == undefined ? "" : o['purchaseCode']) + '</td>'
            body += '<td>' + (o['purchaseNum'] == undefined ? "" : o['purchaseNum']) + '</td>'
            body += '<td>' + (o['price'] == undefined ? "" : o['price']) + '</td>'
            body += '<td>' + (o['purchaseUnit'] == undefined ? "" : o['purchaseUnit']) + '</td>'
            body += '<td>' + (o['convertRate'] == undefined ? "" : o['convertRate']) + '</td>'
            body += '<td>' + (o['purchaseNumCon'] == undefined ? "" : o['purchaseNumCon']) + '</td>'
            body += '<td>' + (o['inStockNum'] == undefined ? "" : o['inStockNum']) + '</td>'
            body += '<td>' + (o['companyEntity'] == undefined ? "" : o['companyEntity']) + '</td>'
            body += '<td>' + (o['notInStockNum'] == undefined ? "" : o['notInStockNum']) + '</td>'
            body += '<td>' + (o['dutyParagraph'] == undefined ? "" : o['dutyParagraph']) + '</td>'
            body += '<td>' + (o['useCompanyName'] == undefined ? "" : o['useCompanyName']) + '</td>'
            body += '<td>' + (o['price'] == undefined ? "" : o['price']) + '</td>'
            body += '<td>' + (o['unit'] == undefined ? "" : o['unit']) + '</td>'
            body += '<td>' + (o['planDeliveryDate'] == undefined ? "" : o['planDeliveryDate']) + '</td>'
            body += '<td>' + (o['providerName'] == undefined ? "" : o['providerName']) + '</td>'
            body += '<td>' + (o['createName'] == undefined ? "" : o['createName']) + '</td>'
            body += '<td>' + (o['infoState'] == 0 ? '未完成' : o['infoState'] == 1 ? '已完成' : '手工完成') + '</td>'
            body += '</tr>'
        })
        tableToXlsx(head, '采购单进度查询', body)
        console.log(table)
    }
}

function tableToXlsx(head: any, filename: any, body: any) {
    const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

    const a = document.createElement('a')
    a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
    a.download = filename
    a.click()
    document.removeChild(a)
}
const handleClick = () => {
    let selsetionList = gridOption.value.getSelectedRows()
    if (selsetionList.length <= 0) {
        Message.warning('请勾选需要打印的数据！')
        return
    }
    printPdf(gridOption.value.getSelectedRows().map((o: any) => { return o['id'] }))
}
//打印预览PDF
const printPdf = (e: any) => {
    post({
        url: 'qms/perchingAnomaly/printPerchingAnomaly',
        data: e,
        responseType: 'blob'
    }).then((res: any) => {
        let reader = new FileReader();
        reader.readAsDataURL(res);
        reader.onload = function () {
            let pdfBase64 = reader.result.replace('data:application/pdf;base64,', '');
            printJS({ printable: pdfBase64, type: 'pdf', base64: true })
        };
    });

}

// 主体下拉框
const focusSelZt = () => {
    handleSearchZt('')
}
const handleSearchZt = (value: any) => {
    if (typeof value == 'object') {
        value = ""
    }
    post({
        url: 'org/baCompany/getFieldValue',
        data: { "company_entity": value },
    }).then(({ code, data, message }: any) => {
        if (code == 200) {
            pageData.companyEntityList = data
        } else {
            Message.error({
                content: message,
                duration: 5000,
            })
        }
    })

}
if (permissionStore.hasPermisson('cgdjdcx.cx1')) {
    pageData.btnList.push('查询')
}

if (permissionStore.hasPermisson('cgdjdcx.dc1')) {
    pageData.btnList.push('导出')
}
</script>
  
<style lang="less" scoped>
.xqdxx {
    display: flex;
}

.isTable {
    margin-top: 100px;
    width: 90%;
    margin: 0 auto;
    border: 1.2px solid #ccc;
    text-align: center;
    border-collapse: collapse;

    td {
        border: 1.2px solid #ccc;
    }

    th {
        border: 1.2px solid #ccc;
    }
}

#dys {
    display: flex;
    width: 90%;
    margin: 0 auto;
    justify-content: space-between;
    font-weight: 1000;

    div {
        width: 200px;
    }
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
</style>